#!/bin/sh
#
# Copyright 2021 EMQ Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# postrm script for kuiper
#
# see: dh_installdeb(1)


# summary of how this script can be called:
#        * <postrm> `remove'
#        * <postrm> `purge'
#        * <old-postrm> `upgrade' <new-version>
#        * <new-postrm> `failed-upgrade' <old-version>
#        * <new-postrm> `abort-install'
#        * <new-postrm> `abort-install' <old-version>
#        * <new-postrm> `abort-upgrade' <old-version>
#        * <disappearer's-postrm> `disappear' <overwriter>
#          <overwriter-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

set -e -u

case "$1" in
    purge)
        rm -f /etc/default/kuiper

        if command -v systemctl >/dev/null 2>&1; then
            systemctl disable kuiper
            systemctl stop kuiper
        fi

        if [ -d /var/lib/kuiper ]; then
                rm -r /var/lib/kuiper
        fi
        if [ -d /var/log/kuiper ]; then
                rm -r /var/log/kuiper
        fi
        if [ -d /var/run/kuiper ]; then
                rm -r /var/run/kuiper
        fi
        if [ -d /etc/kuiper ]; then
                rm -r /etc/kuiper
        fi
        if [ -e /etc/init.d/kuiper ]; then
                rm  /etc/init.d/kuiper
        fi
        if [ ! -z "$(ls /var/lib/dpkg/info/ | grep kuiper)" ]; then
            rm -rf $(ls /var/lib/dpkg/info/ | grep kuiper)
        fi
        # Remove User & Group, killing any process owned by them
        if getent passwd kuiper >/dev/null; then
                pkill -u kuiper || true
                deluser --quiet --system kuiper
        fi
        if getent group kuiper >/dev/null; then
                delgroup --quiet --system --only-if-empty kuiper || true
        fi
        if [ -f /usr/bin/kuiper ]; then
                rm /usr/bin/kuiper
        fi
        if [ -f /usr/bin/kuiperd ]; then
                rm /usr/bin/kuiperd
        fi
    ;;

    remove)
        if [ -f /usr/bin/kuiper ]; then
                rm /usr/bin/kuiper
        fi
        if [ -f /usr/bin/kuiperd ]; then
                rm /usr/bin/kuiperd
        fi
    ;;

    upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
    ;;

    *)
        echo "postrm called with unknown argument \`$1\`" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
